const http = require('http')
const fs = require('fs')
const path = require("path")
const qs = require('querystring')

const port = 8080


const server = http.createServer((req, res) => {
    const url = req.url
    res.statusCode = 200
    let data = ''
    req.on('data', chunk => {
        data += chunk  // 将接收到的数据暂时保存起来
    })
    req.on('end', () => {
        if (url == "/checklogin" && data) {
            //处理登陆逻辑
            if (checkLogin(data)) {
                res.end('登陆成功！！！\n')
            }

            else {
                res.end('登陆失败！！！\n')
            }
        } else if (url == "/reg" && data) {
            if (reg(data)) {
                res.end('注册成功！！！\n')
            }

            else {
                res.end('注册失败！！！\n')
            }

        } else if (url == "/userlist") {
            fs.createReadStream("./data/user.json").pipe(res)

        } else if (url.indexOf("/deluser") != -1) {// /deluser?id=2

            let uArray = url.split('?')

            let q = qs.parse(uArray[1])

            let jsonStr = fs.readFileSync("./data/user.json", "utf8").toString()
            let jArray = JSON.parse(jsonStr) //解析json字符串为user对象数组
            jArray = jArray.filter(item => {
                return item.id != q.id
            })
            fs.writeFileSync("./data/user.json", JSON.stringify(jArray))
            res.end('成功删除！！！')
        } else {
            returnByUrl(res, url)
        }
    })

    //全站 全栈

    //console.log(req.body)

    //res.end('你好世界\n')
})

server.listen(port, () => {
    console.log(`服务器运行在 http://localhost:${port}/`)
})
function checkLogin(data) {

    const user = JSON.parse(data) // 数据传输完，打印数据的内容
    // console.log(data)

    // const readStream = fs.createReadStream("./data/user.json", "utf8")


    let findUser = false //标记是否找到用户
    let jsonStr = fs.readFileSync("./data/user.json", "utf8").toString()
    const jArray = JSON.parse(jsonStr) //解析json字符串为user对象数组

    jArray.forEach(element => {     //循环遍历user对象数组里的每一个元素
        if (user.username === element.username && user.pwd === element.pwd) {
            findUser = true
            // break//找到后，退出遍历
        }
    });


    // readStream.on("data", chunkdata => {
    //     jsonStr += chunkdata

    // })
    // 
    // readStream.on('end', () => {

    // })

    return findUser

}

function reg(data) {

    const user = JSON.parse(data) // 数据传输完，打印数据的内容
    // console.log(data)

    // const readStream = fs.createReadStream("./data/user.json", "utf8")
    let isUserExists = false //标记是否找到用户
    let jsonStr = fs.readFileSync("./data/user.json", "utf8").toString()
    const jArray = JSON.parse(jsonStr) //解析json字符串为user对象数组
    let maxId = 0
    jArray.forEach(element => {     //循环遍历user对象数组里的每一个元素

        if (maxId < element.id) {
            maxId = element.id
        }
        if (user.username === element.username) {
            isUserExists = true
            // break//找到后，退出遍历
        }
    });

    if (isUserExists) {
        return false
    }
    else {
        user.id = maxId + 1
        jArray.push(user)
        fs.writeFileSync("./data/user.json", JSON.stringify(jArray))
        return true
    }



}
function returnByUrl(res, url) {
    const ext = path.extname(url)
    switch (ext) {
        case ".html":
            res.setHeader('Content-Type', 'text/html;charset=utf8')
            fs.createReadStream(__dirname + url, 'utf8').pipe(res)
            break
        case ".css":
            res.setHeader('Content-Type', 'text/css;charset=UTF-8')
            fs.createReadStream(__dirname + url, 'utf8').pipe(res)
            break
        case ".js":
            res.setHeader('Content-Type', 'application/x-javascript')
            fs.createReadStream(__dirname + url, 'utf8').pipe(res)
            break
        default:
            res.setHeader('Content-Type', 'text/html;charset=utf8')
            fs.createReadStream(__dirname + "/index.html", 'utf8').pipe(res)
            break
    }
}
